import request from "../../common/utils/request";

const contract = {
  state: {
    /**
     * @description: 添加合同
     */
    // 合同下拉初始化
    contractInitOpt: {},
    // 选择的合同模板类型映射的默认条款类型
    defaultClause: [],
    initClauseType: [], // 初始化时对应的条款类型
    // 条款列表
    clauseList: [],
    // 表单数据
    addFormData: {
      // 基本信息
      basicInfo: {},
      // 费用条款
      feeClause: {},
      // 合同文本
      contractText: {},
    },
    editContractId: 0,
    // 添加合同 当前步骤
    currentStep: 0,
    // 是否触发表单验证
    validateTrigger: false,
    // 条款tab个数
    clauseTabCount: {},
    // 每个tab表单内容
    clauseContentList: {},
    // 当前合同起始日期
    contractDateRange: {
      startDate: "",
      endDate: "",
      lastEndDate: "",
    },
    addPageLoading: false,
    // 税率
    taxRateMap: {},
    // 是否跨楼宇选择了
    multiBuild: false,
    // 已选房源数据
    checkedRoomList: [],
    paneCheckedRoom: {},
    currentBuildId: [],
    currentProjectId: 0,
    /**
     * @description: 合同详情
     */
    contractDetail: {},
    // 最新备注
    latestRemark: "",
    lastActiveTab: "basicInfo",
    contractType: "", //合同类型
    clearRentDetail: false, //是否要清空新建合同的租金明细

    // 自定义合同模板
    tplContent: {},
    tplInitData: {},
    currentContractTpl: {},

    // 审批
    approvalListInit: {},

    // 房源详情
    // 触发更新租控管理左侧树的更新
    refreshTreeTrigger: 0,
    refreshTreeParams: {},

    contractListUpdate: false, //是否更新合同列表
    contractListInit: false, //是否初始化合同列表
    draftContractListInit: false, //是否初始化草稿合同列表
    contractAddDraft: {},  // 新增时保存的本地草稿
    useDraft: null, // 新增时是否使用保存的本地草稿
  },
  mutations: {
    SET_MC_TREE_REFRESH: (state, params) => {
      state.refreshTreeParams = params;
      state.refreshTreeTrigger++;
    },
    SET_INIT_OPT: (state, data) => {
      state.contractInitOpt = { ...data };
    },
    REMOVE_INIT_OPT: (state) => {
      state.contractInitOpt = {};
    },
    SET_DEFAULT_CLAUSE: (state, data = []) => {
      state.defaultClause = data;
    },
    SET_INIT_CLAUSE_TYPE: (state, data = []) => {
      state.initClauseType = data;
    },
    SET_CLAUSE_LIST: (state, list) => {
      state.clauseList = list;
    },
    SET_FORM_DATA: (state, { key, data }) => {
      if (!state.addFormData[key]) {
        state.addFormData[key] = {};
      }
      state.addFormData[key] = { ...state.addFormData[key], ...data };
    },
    SET_CURRENT_EDIT_ID: (state, id) => {
      state.editContractId = id;
    },
    SET_CURRENT_STEP: (state, step) => {
      state.currentStep = step;
      state.validateTrigger = false;
    },
    SET_VALIDATE_TRIGGER: (state, value) => {
      state.validateTrigger = value;
    },
    // type "add" "reduce"
    SET_CLAUSE_TAB_COUNT: (state, { key, type }) => {
      if (state.clauseTabCount[key]) {
        if (type == "add") {
          state.clauseTabCount[key].count++;
        } else {
          if (state.clauseTabCount[key].count == 1) {
            delete state.clauseTabCount[key];
          } else {
            state.clauseTabCount[key].count--;
          }
        }
      } else {
        state.clauseTabCount[key] = { count: 1 };
      }
    },
    SET_CLAUSE_TAB_CHECKEDKEYS: (state, { key, keys }) => {
      state.clauseTabCount[key].checkedKeys = keys;
    },
    SET_CLAUSE_CONTENT_CHANGED: (state, { key, changed }) => {
      state.clauseContentList[key].changed = changed;
    },
    SET_CLAUSE_CONTENT: (state, { key, content, type }) => {
      if (type == "add") {
        state.clauseContentList[key] = content;
      }
      if (type == "reduce") {
        delete state.clauseContentList[key];
      }
    },
    CLEAR_CLAUSE_CONTENT: (state) => {
      state.clauseTabCount = {};
      state.clauseContentList = {};
      state.paneCheckedRoom = {};
    },
    SET_CLAUSE_CONTENT_BY_KEY: (state, { key, dataObj }) => {
      const { content } = state.clauseContentList[key];
      for (let k in dataObj) {
        content[k] = dataObj[k];
      }
    },
    SET_CONTRACT_DATE_RANGE: (state, data) => {
      for (let key in data) {
        state.contractDateRange[key] = data[key];
      }
    },
    SET_ADD_PAGE_LOADING: (state, loading) => {
      state.addPageLoading = loading;
    },
    RESET_CONTRACT_INFO: (state) => {
      state.addFormData.basicInfo = {};
      state.addFormData.feeClause = {};
      state.addFormData.contractText = {};
      state.currentStep = 0;
      state.editContractId = 0;
      state.clauseTabCount = {};
      state.clauseContentList = {};
      state.contractDateRange = {
        startDate: "",
        endDate: "",
        lastEndDate: "",
      };
      state.clearRentDetail = false;
      state.tplContent = {};
      state.contractAddDraft = {};
      state.useDraft = null;
    },
    SET_CONTRACT_DETAIL: (state, detail) => {
      state.contractDetail = detail;
    },
    SET_LATEST_REMARK: (state, data) => {
      state.latestRemark = data;
    },
    SET_CONTRACT_RETREAT_ABSTRACT: (state, data) => {
      state.contractRetreatAbstract = data;
    },
    SET_DETAIL_ACTIVE_TAB: (state, tab) => {
      state.lastActiveTab = tab;
    },
    SET_TAX_RATE_MAP: (state, data) => {
      if (data) {
        state.taxRateMap[data.key] = data.value;
      } else {
        state.taxRateMap = {};
      }
    },
    SET_CONTRACT_TYPE: (state, data) => {
      state.contractType = data;
    },
    SET_CLEAR_RENT_DETAIL: (state, data) => {
      state.clearRentDetail = data;
    },
    SET_MULTI_BUILD: (state, mbFlag) => {
      state.multiBuild = mbFlag;
    },
    SET_CHECKED_ROOM_LIST: (state, list) => {
      state.checkedRoomList = list;
    },
    SET_PANE_CHECKED_ROOM: (state, params) => {
      const { clauseId, type, roomIds } = params;
      if (type == "add") {
        if (!state.paneCheckedRoom[clauseId]) {
          state.paneCheckedRoom[clauseId] = {
            checkedIds: [],
          };
        }
        // 批量添加
        if (roomIds.length) {
          state.paneCheckedRoom[clauseId].checkedIds = [
            ...state.paneCheckedRoom[clauseId].checkedIds,
            ...roomIds,
          ];
        }
      }
      if (type == "remove") {
        // 只能单独删除
        const idx = state.paneCheckedRoom[clauseId]?.checkedIds?.findIndex(
          (item) => item == roomIds
        );
        if (idx || idx == 0) {
          state.paneCheckedRoom[clauseId].checkedIds.splice(idx, 1);
        }
      }
    },
    CLEAR_PANE_CHECKED_ROOM: (state) => {
      state.paneCheckedRoom = {};
    },
    SET_CURRENT_BUILD: (state, { buildIds, projectId }) => {
      state.currentBuildId = buildIds;
      state.currentProjectId = projectId;
    },
    SET_TPL_CONTENT: (state, info) => {
      state.tplContent = info;
    },
    SET_TEMPLATE_INIT: (state, initInfo = {}) => {
      state.tplInitData = { ...state.tplInitData, ...initInfo };
    },
    REMOVE_TEMPLATE_INIT: (state) => {
      state.tplInitData = {};
    },
    SET_CURRENT_CONTRACT_TEMPLATE: (state, detail) => {
      state.currentContractTpl = detail;
    },
    SET_APPROVAL_LIST_INIT: (state, data) => {
      state.approvalListInit = data;
    },
    SET_CONTRACT_LIST_UPDATE: (state, data) => {
      state.contractListUpdate = data;
    },
    SET_CONTRACT_LIST_INIT: (state, data) => {
      state.contractListInit = data;
    },
    SET_DRAFT_CONTRACT_LIST_INIT: (state, data) => {
      state.draftContractListInit = data;
    },
    SET_CONTRACT_ADD_DRAFT: (state, data) => {
      state.contractAddDraft = data;
    },
    SET_USE_DRAFT: (state, data) => {
      state.useDraft = data;
    },
  },
  actions: {
    // 添加合同数据初始化
    ContractInit: ({ state, commit, dispatch }) => {
      return new Promise((resolve) => {
        const { contractInitOpt } = state;
        if (
          contractInitOpt &&
          contractInitOpt.all_industry &&
          contractInitOpt.followup
        ) {
          resolve(contractInitOpt);
        } else {
          let result = {};
          const success = (res) => {
            result = { ...result, ...res };
            if (result.all_industry && result.followup) {
              commit("SET_INIT_OPT", result);
              resolve(result);
            }
          };
          request.get("/org", "/contract/createInit").then((res) => {
            success(res.data);
          });
          dispatch("GetIndustryList").then((list) => {
            success({ all_industry: list });
          });
        }
      });
    },
    RemoveContractInit: ({ commit }) => {
      return new Promise((resolve) => {
        commit("REMOVE_INIT_OPT");
        resolve();
      });
    },
    // 获取所有条款
    GetAllClause: ({ state, commit }) => {
      return new Promise((resolve) => {
        // const { clauseList } = state;
        // if (clauseList.length) {
        //   resolve(clauseList);
        // } else {
        request.get("/org", "/contract/clause").then((res) => {
          commit("SET_CLAUSE_LIST", res.list);
          resolve(res.list);
        });
        // }
      });
    },
    // 获取成本合同条款
    GetCostClause: ({ state, commit }) => {
      return new Promise((resolve) => {
        // const { clauseList } = state;
        // if (clauseList.length) {
        //   resolve(clauseList);
        // } else {
        request.get("/org", "/contract/clause", { op_type: 4 }).then((res) => {
          commit("SET_CLAUSE_LIST", res.list);
          resolve(res.list);
        });
        // }
      });
    },
    // 选择的模板
    SetDefaultClause: ({ commit }, data) => {
      return new Promise((resolve) => {
        if (data) {
          commit("SET_DEFAULT_CLAUSE", scenceToClause[data.scene]);
        } else {
          commit("SET_DEFAULT_CLAUSE");
        }
        resolve();
      });
    },
    SetInitClauseType: ({ commit }, data) => {
      return new Promise((resolve) => {
        if (data) {
          commit("SET_INIT_CLAUSE_TYPE", scenceToClause[data.scene]);
        } else {
          commit("SET_INIT_CLAUSE_TYPE");
        }
        resolve();
      });
    },
    // 验证后的表单数据
    SetAddFormData: ({ commit }, { key, data }) => {
      commit("SET_FORM_DATA", { key, data });
    },
    SetAllAddFormData: ({ commit }, data) => {
      return new Promise((resolve) => {
        for (let key in data) {
          commit("SET_FORM_DATA", { key, data: data[key] });
        }
        resolve();
      });
    },
    // 当前编辑的contract id
    SetEditContractId: ({ commit }, id) => {
      commit("SET_CURRENT_EDIT_ID", id);
    },
    // 触发表单验证
    SetValidateTrigger: ({ commit }, value = true) => {
      return new Promise((resolve) => {
        commit("SET_VALIDATE_TRIGGER", value);
        resolve();
      });
    },
    // 设置当前step
    SetCurrentStep: ({ commit }, { step }) => {
      commit("SET_CURRENT_STEP", step);
    },
    // 设置条款内容
    SetClauseContent: ({ commit }, { type, content, key }) => {
      return new Promise((resolve) => {
        if (key) {
          commit("SET_CLAUSE_CONTENT_BY_KEY", { key, content });
        } else {
          commit("SET_CLAUSE_TAB_COUNT", { key: content.id, type });
          commit("SET_CLAUSE_CONTENT", { key: content.key, content, type });
        }
        resolve();
      });
    },
    ClearClauseContent: ({ commit }) => {
      return new Promise((resolve) => {
        commit("CLEAR_CLAUSE_CONTENT");
        resolve();
      });
    },
    // 设置当前选中的room key (type: replace || reduce || add)
    SetClauseCheckedRoomKey: ({ state, commit }, { key, keys, type }) => {
      return new Promise((resolve) => {
        let clauseTab = state.clauseTabCount[key];
        let hasCheckedList = [];
        if (type == "reduce") {
          clauseTab.checkedKeys = reduceArrayItem(clauseTab.checkedKeys, keys);
          console.log("SetClauseCheckedRoomKey", clauseTab.checkedKeys);
        } else {
          if (!clauseTab.checkedKeys || !clauseTab.checkedKeys.length) {
            clauseTab.checkedKeys = keys;
          } else {
            for (let key of keys) {
              if (clauseTab.checkedKeys.includes(key)) {
                hasCheckedList.push(key);
              } else {
                clauseTab.checkedKeys.push(key);
              }
            }
          }
        }
        commit("SET_CLAUSE_TAB_CHECKEDKEYS", {
          key,
          keys: clauseTab.checkedKeys,
        });
        resolve({
          unCheckableList: hasCheckedList,
          checkedKeys: clauseTab.checkedKeys,
        });
      });
    },
    // 当前表单是否已经被修改过
    SetClauseTabChange: ({ commit }, { key, changed }) => {
      commit("SET_CLAUSE_CONTENT_CHANGED", { key, changed });
    },
    // 设置合同起止时间 （用于条款时间判断）
    SetContractDateRange: ({ commit }, data) => {
      commit("SET_CONTRACT_DATE_RANGE", data);
    },
    // 页面loading状态
    SetAddPageLoading: ({ commit }, loading) => {
      commit("SET_ADD_PAGE_LOADING", loading);
    },
    // 重置添加数据
    ResetAddForm: ({ commit }) => {
      commit("RESET_CONTRACT_INFO");
    },
    // 存储订单详情
    SetContractDetail: ({ commit }, detail) => {
      commit("SET_CONTRACT_DETAIL", detail);
    },
    // 存储最新备注
    SetLatestRemark: ({ commit }, data) => {
      commit("SET_LATEST_REMARK", data);
    },
    // 存储订单退租摘要
    SetContractRetreatAbstract: ({ commit }, data) => {
      commit("SET_CONTRACT_RETREAT_ABSTRACT", data);
    },
    // 设置上一次选中tab
    SetLastActiveTab: ({ commit }, activeTab) => {
      commit("SET_DETAIL_ACTIVE_TAB", activeTab || "basicInfo");
    },
    // 设置同类型条款的税率
    SetTaxRateMap: ({ commit }, data) => {
      commit("SET_TAX_RATE_MAP", data);
    },
    // 存储最新合同类型
    SetContractType: ({ commit }, data) => {
      commit("SET_CONTRACT_TYPE", data);
    },
    // 存储是否要清空新建合同的租金明细
    SetClearRentDetail: ({ commit }, data) => {
      commit("SET_CLEAR_RENT_DETAIL", data);
    },
    // 是否是跨楼宇选择房间
    SetMultiBuild: ({ commit }, mbFlag) => {
      commit("SET_MULTI_BUILD", mbFlag);
    },
    SetCurrentBuildId: ({ commit }, data) => {
      commit("SET_CURRENT_BUILD", data);
    },

    SetCheckedRoomList: ({ commit }, list) => {
      commit("SET_CHECKED_ROOM_LIST", list);
    },
    SetPaneCheckedRoom: ({ commit }, { clauseId, type, roomIds }) => {
      commit("SET_PANE_CHECKED_ROOM", { clauseId, type, roomIds });
    },
    GetPaneCheckedRoom: ({ state }, clauseId) => {
      return new Promise((resolve) => {
        resolve(state.paneCheckedRoom[clauseId]);
      });
    },
    // 清除所有PaneCheckedRoom
    ClearPaneCheckedRoom: ({ commit }) => {
      commit("CLEAR_PANE_CHECKED_ROOM");
    },
    // 自定义模板详情
    SetTplContent: ({ commit }, info) => {
      commit("SET_TPL_CONTENT", info);
    },
    GetTemplateInit: ({ state, commit }) => {
      return new Promise((resolve) => {
        if (Object.keys(state.tplInitData).length) {
          resolve(state.tplInitData);
        } else {
          let count = 0;
          let result = {};
          const success = (data) => {
            const transData = transValueKey(data);
            result = {
              ...result,
              ...transData,
            };
            count++;
            if (count == 2) {
              commit("SET_TEMPLATE_INIT", result);
              resolve(result);
            }
          };
          request
            .get("/org", "/contract/init")
            .then((res) => success(res.initData));
          request
            .get("/org", "/contract/createInit")
            .then((res) => success(res.data));
        }
      });
    },
    RemoveTemplateInit: ({ commit }) => {
      return new Promise((resolve) => {
        commit("REMOVE_TEMPLATE_INIT");
        resolve();
      });
    },
    SetCurrentCT: ({ commit }, detail) => {
      return new Promise((resolve) => {
        commit("SET_CURRENT_CONTRACT_TEMPLATE", detail);
        resolve();
      });
    },

    SetApprovalListInit: ({ state, commit }) => {
      return new Promise((resolve) => {
        const { approvalListInit } = state;
        if (Object.keys(approvalListInit).length) {
          resolve(approvalListInit);
        } else {
          request.get("/org", "/workbench/approveListInit").then((res) => {
            commit("SET_APPROVAL_LIST_INIT", res.returnData);
            resolve(res.returnData);
          });
        }
      });
    },

    /** 更新租控中心左侧树 */
    RefreshMCTree: ({ commit }, params) => {
      return new Promise((resolve) => {
        commit("SET_MC_TREE_REFRESH", params);
        resolve();
      });
    },
    /** 更新合同列表 */
    SetContractListUpdate: ({ commit }, params) => {
      return new Promise((resolve) => {
        commit("SET_CONTRACT_LIST_UPDATE", params);
        resolve();
      });
    },
    /** 重置合同列表 */
    SetContractListInit: ({ commit }, params) => {
      return new Promise((resolve) => {
        commit("SET_CONTRACT_LIST_INIT", params);
        resolve();
      });
    },
    /** 重置草稿列表 */
    SetDraftContractListInit: ({ commit }, params) => {
      return new Promise((resolve) => {
        commit("SET_DRAFT_CONTRACT_LIST_INIT", params);
        resolve();
      });
    },
    // 合同新增时本地草稿
    SetContractAddDraft: ({ commit }, info) => {
      return new Promise((resolve) => {
        commit("SET_CONTRACT_ADD_DRAFT", info);
        resolve();
      });
    },
    SetUseDraft: ({ commit }, info) => {
      return new Promise((resolve) => {
        commit("SET_USE_DRAFT", info);
        resolve();
      });
    },
  },
};

const reduceArrayItem = (mainArr, arr) => {
  if (!arr.length) {
    return mainArr;
  }
  let result = [];
  if (!mainArr) {
    return result;
  }
  mainArr.forEach((item) => {
    if (!arr.includes(item)) {
      result.push(item);
    }
  });
  return result;
};

const scenceToClause = {
  CONTRACT_2: ["lease", "property"],
  CONTRACT_3: ["property"],
  CONTRACT_4: ["lease"],
};

const transValueKey = (data = {}, value = "key", label = "name") => {
  let result = {};
  for (let dataKey in data) {
    result[dataKey] = data[dataKey].map((item) => ({
      label: item[label],
      value: item[value],
    }));
  }
  return result;
};
export default contract;
